import 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:template/config/config.dart';

enum ContentType {
  json,
  formUrlEncoded,
  queryString,
}

class HttpUtil {
  static bool isModalShown = false;
  static Config config = Config();

  static Future<Map<String, dynamic>> request({
    required String url,
    String method = 'GET',
    Map<String, dynamic>? params,
    dynamic data,
    bool requireAuth = true,
    ContentType contentType = ContentType.json,
  }) async {
    // 1. 准备请求头
    final headers = await _prepareHeaders(requireAuth);

    // 根据内容类型设置Content-Type
    headers['Content-Type'] = _getContentTypeHeader(contentType);

    // 2. 构建完整URL
    Uri fullUrl = Uri.parse('${config.baseUrl}$url');

    // 处理查询参数
    if (contentType == ContentType.queryString && params != null) {
      fullUrl = fullUrl.replace(queryParameters: params);
    }

    // 3. 处理请求参数
    http.Response response;
    try {
      switch (method.toUpperCase()) {
        case 'GET':
          // GET请求总是使用查询参数
          fullUrl = fullUrl.replace(queryParameters: params);
          response = await http
              .get(
                fullUrl,
                headers: headers,
              )
              .timeout(const Duration(seconds: 30));
          break;

        case 'POST':
          response = await http
              .post(
                fullUrl,
                headers: headers,
                body: _encodeBody(data, contentType),
              )
              .timeout(const Duration(seconds: 30));
          break;

        case 'PUT':
          response = await http
              .put(
                fullUrl,
                headers: headers,
                body: _encodeBody(data, contentType),
              )
              .timeout(const Duration(seconds: 30));
          break;

        case 'DELETE':
          response = await http
              .delete(
                fullUrl,
                headers: headers,
              )
              .timeout(const Duration(seconds: 30));
          break;

        default:
          throw Exception('Unsupported HTTP method: $method');
      }

      // 4. 处理响应
      return _handleResponse(response);
    } catch (e) {
      // 5. 错误处理
      return _handleError(e);
    }
  }

  static String _getContentTypeHeader(ContentType type) {
    switch (type) {
      case ContentType.json:
        return 'application/json';
      case ContentType.formUrlEncoded:
        return 'application/x-www-form-urlencoded';
      case ContentType.queryString:
        return 'application/x-www-form-urlencoded'; // 查询字符串也使用这个类型
    }
  }

  static dynamic _encodeBody(dynamic data, ContentType contentType) {
    if (data == null) return null;

    switch (contentType) {
      case ContentType.json:
        return json.encode(data);
      case ContentType.formUrlEncoded:
        return Uri(queryParameters: data as Map<String, String>).query;
      case ContentType.queryString:
        return null; // 查询字符串不设置请求体
    }
  }

  static Future<Map<String, String>> _prepareHeaders(bool requireAuth) async {
    final headers = {
      'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
      'Verify-Code': _getVerifyCode(),
      'Login-Platform': '3',
    };

    if (requireAuth) {
      final tokens = await getTokens();
      headers['Blade-Auth'] = tokens['access_token'] ?? '';
    }

    return headers;
  }

  static Map<String, dynamic> _handleResponse(http.Response response) {
    developer.log('HTTP ${response.statusCode}: ${response.request?.url}');

    // 处理401未授权
    if (response.statusCode == 401) {
      _showLoginModal();
      throw Exception('Unauthorized: 请重新登录');
    }

    // 处理404
    if (response.statusCode == 404) {
      throw Exception('请求地址不存在: ${response.request?.url}');
    }

    // 处理其他错误状态码
    if (response.statusCode < 200 || response.statusCode >= 300) {
      throw Exception('HTTP错误 ${response.statusCode}: ${response.body}');
    }

    // 解析响应体
    try {
      return json.decode(response.body);
    } catch (e) {
      throw Exception('响应解析失败: $e');
    }
  }

  static void _showLoginModal() {
    if (isModalShown) return;
    isModalShown = true;

    // 使用全局navigatorKey跳转到登录页
    navigatorKey.currentState?.pushNamedAndRemoveUntil(
      '/login',
      (route) => false,
    );

    // 3秒后重置状态
    Future.delayed(const Duration(seconds: 3), () {
      isModalShown = false;
    });
  }

  static Map<String, dynamic> _handleError(dynamic error) {
    if (error is TimeoutException) {
      throw Exception('请求超时，请检查网络连接');
    } else if (error.toString().contains('SocketException')) {
      throw Exception('网络异常，请检查网络连接');
    } else {
      throw Exception('未知错误: $error');
    }
  }

  static String _getVerifyCode() {
    final timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    final reversedTimestamp = timestamp.split('').reversed.join('');
    return base64.encode(utf8.encode(reversedTimestamp));
  }

  // 全局导航Key（需要在main.dart中初始化）
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
}

// 获取token的辅助函数（从shared_preferences）
Future<Map<String, String?>> getTokens() async {
  final prefs = await SharedPreferences.getInstance();
  return {
    'access_token': prefs.getString('access_token'),
    'refresh_token': prefs.getString('refresh_token'),
    'user_name': prefs.getString('user_name'),
  };
}
